package com.andaily.web.controller.mobile.account;

import com.andaily.domain.dto.account.AccountTypeDTO;
import com.andaily.service.AccountService;
import com.andaily.web.controller.validator.AccountTypeFormValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/account_type/form")
public class AccountTypeFormController {

    private AccountService accountService;
    private AccountTypeFormValidator validator;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(String guid, ModelMap model) {
        AccountTypeDTO accountType = accountService.loadAccountType(guid);
        model.addAttribute("accountType", accountType);
        return "account/type/account_type_form";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("accountType") AccountTypeDTO accountType, BindingResult result) {
        validator.validate(accountType, result);
        if (result.hasErrors()) {
            return "account/type/account_type_form";
        }
        accountService.persistAccountType(accountType);
        return "redirect:/m/account_type/overview";
    }


    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Autowired
    public void setValidator(AccountTypeFormValidator validator) {
        this.validator = validator;
    }
}
